package users

import (
	"cloud_android_backend/pkg/models/users"
	"github.com/golang/glog"
	"github.com/jinzhu/gorm"
	"github.com/lithammer/shortuuid"
	"modules.tenxcloud.com/common/composite"
	"strings"
)

func GetUserByAccessKey(db *gorm.DB, accessKey string) (*users.UserCredentials, error) {
	uc := users.NewUserCredential()
	err := uc.GetByAccessKey(db, accessKey)
	return uc, err
}

func GenerateAkSk(db *gorm.DB, userId string) (*users.UserCredentials, error) {
	accessKey := strings.ToUpper(shortuuid.New()[:20])
	secretKey := strings.Replace(shortuuid.New()+shortuuid.New(), "-", "", -1)[:40]
	userCredential := users.NewUserCredential()
	userCredential.AccessKey = accessKey
	userCredential.SecretKey = secretKey
	userCredential.UserId = userId
	userCredential.Status = 1
	err := userCredential.Create(db)
	if err != nil {
		return nil, err
	}
	return userCredential, nil
}

func StopCredentialStatus(id int64) error {
	db, err := composite.Database.GetOrm()
	if err != nil {
		glog.Errorf("get orm failed, error %v", err)
		return err
	}
	userCredential := users.NewUserCredential()
	return userCredential.UpdateCredential(db, id, map[string]interface{}{"status": 0})

}
